package com.godo.test.downfile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import com.godo.test.Base;

public abstract class DownImage extends Base{

//	public abstract void downImageFromUrl(String url,String out,String cls) throws InterruptedException, IOException ;

	public abstract void downImageFromUrl(String url,File outDir) throws InterruptedException, IOException ;
	
	public abstract ArrayList<String> getUrls(String url,String code) throws IOException ;
	
	public abstract File getOutDir(String url,File outDir) ;
	
	public void downImage(String url,File outDir) throws IOException{
		File file = isDownFile(outDir, url);
		if(file!=null){
			super.downFile(url, file) ;
		}
	}
	
	private File isDownFile(File file,String url){
		String fname = url.substring(url.lastIndexOf("/")+1) ;
		try {
			fname = java.net.URLDecoder.decode(fname,"utf-8") ;
			fname = fname.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\?", "") ;
		} catch (Exception e1) {
			return null ;
		}

		try {
			createFile(file) ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new File(file,fname) ;
	}
	
	protected void deleteDirectory(String file){
		File f = new File(file) ;
		if(f.exists()){
			deleteDirectory(f) ;
		}
	}
	protected void deleteDirectory(File file){
		if(file.isDirectory()){
			File[] files = file.listFiles() ;
			if(files!=null)
			for(File f:files){
				if(f.isDirectory()){
					deleteDirectory(f) ;
				} else {
					f.delete() ;
				}
			}
		}
		if(file.exists()){
			file.delete() ;
		}
//		file.deleteOnExit() ;
	}
	
	private void createFile(File file) throws IOException{
		if(file.exists()){
			return ;
		}
		file.mkdirs() ;
	}
}
